package com.yishusmt.wechatapi.wechatdev.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangyi
 * @date 2018/8/8 9:43
 */
@Slf4j
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 将数据存入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value){
        boolean flag = false;
        try {
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key, value);
            flag = true;
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return flag;
    }

    /**
     * 数据存入缓存后设置过期时间（秒）
     *
     * @param key
     * @param value
     * @param expireTime
     * @return
     */
    public boolean set(final String key, Object value,Long expireTime){
        boolean flag = false;
        try{
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key,value,expireTime,TimeUnit.SECONDS);
            flag = true;
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return flag;
    }

    /**
     * 获取缓存数据
     *
     * @param key
     * @param <T>
     * @return
     */
    public <T> T get(final String key){
        T result = null;
        ValueOperations<Serializable,T> valueOperations = redisTemplate.opsForValue();
        result = valueOperations.get(key);
        return result;
    }

    /**
     * 判断缓存中是否存在此数据
     *
     * @param key
     * @return
     */
    public boolean exists(final String key){
        Boolean aBoolean = redisTemplate.hasKey(key);
        return aBoolean;
    }

    /**
     * 删除缓存中的数据
     *
     * @param key
     * @return
     */
    public boolean del(final String key){
        Boolean delete = redisTemplate.delete(key);
        return delete;
    }
}
